/*
 * Copyright (C) 2012 DataSymphony (http://datasymphony.com.au)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package au.com.ds.restty.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import au.com.ds.restty.exc.FileIOError;

public class Utils {
	public static final String EOL = System.getProperty("line.separator");

	private Utils(){}
	
	public static int copyStream(InputStream is, StringBuilder sb){
		byte[] buff = new byte[10*1024];
		int bytes = 0;
		try {
			while ((bytes = is.read(buff)) > 0){
				String str = new String(buff, 0, bytes);
				sb.append(str);
			}
		} catch (Exception e) {
			throw new FileIOError("Error reading from stream", e);
		}
		
		return bytes;
	}
	
	public static String dupString(String str, int times){
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < times; i++){
			sb.append(str);
		}
		
		return sb.toString();
	}
	
	public static boolean isValidJsIdentifier(String str){
		return str.matches("[a-zA-Z_$][0-9a-zA-Z_$]*");
	}
	
	public static String getScript(File file){
		String result = null;
		FileInputStream is = null;
		try {
			is = new FileInputStream(file);
			StringBuilder sb = new StringBuilder();
			Utils.copyStream(is, sb);
			result = sb.toString();
		} catch (Exception e) {
			throw new FileIOError("Error reading script file", e);
		} finally {
			if (is != null){
				try { is.close(); } catch (IOException e) {}
			}
		}
		
		return result;
	}

}
